<?php
namespace jy_boaoshop;
defined('BY_JYA') or exit('error');
/*
	分红插件会员类
	如果将分红商各项数据在每次数据变动时计算好并存入数据库。
	那么分别需要做
		在设置上下级关系时，修改新上级的 下线数量、分红商数量、订单数量、订单佣金数量等数据
		在变更上下级关系时，修改原、新上级的各项参数
		在发生订单时，修改上级的订单相关参数
		在用户成为分红商时，修改上级的分红商数量相关数据
*/
class member extends \plugin{
	/*
		核实分红商,$isset无条件成为分红商
	*/
	public function checkmember($mid=0,$isexi=false,$isset=false){
			$mid=$mid?:$_SESSION['uid'];
			$member=$this->get('member',array('mid'=>$mid,'uniacid'=>$_SESSION['uniacid']));			
			$page_setting=$this->plugin_setting('page_setting');
			$page_setting['tagent']=$page_setting['tagent']?:'代理商';
			if(!$member['mid']){
				$this->register(array('mid'=>$mid));
				$member=$this->get('member',array('mid'=>$mid));
			}
			if(!$member['is_agent']){
				//如果成为分红商无条件，此处自动申请成为分红商
				if($this->setting['become']==0 || $isset || $this->session('becomefromuser')){
					//分红商无需审核，此处自动审核
					$ispass=true;
					$this->apply_agent($member['mid']);
					if($this->setting['become_check'] && $isexi){
						exi('申请正在审核请耐心等待！','error','jy_boaoshop/apply/');
					}elseif($isset){
						return true;
					}
				}elseif($this->setting['become']==2){
					//消费次数
					$buynums=pdo_count('jy_boaoshop_order',array('ispay'=>1,'mid'=>$mid,'uniacid'=>$_SESSION['uniacid']),'id');
					if($buynums>=$this->setting['num']){
						$ispass=true;
						$this->apply_agent($member['mid']);
						if($this->setting['become_check'] && $isexi){
							exi('申请正在审核请耐心等待。','error','jy_boaoshop/apply/');
						}
					}elseif($isexi){
						exi('你还不是'.$page_setting['tagent'].'，请前往申请！','error','jy_boaoshop/apply/');
					}
				}elseif($this->setting['become']==3){
					//消费金额
					$buyfee=pdo_getsum('jy_boaoshop_order',array('ispay'=>1,'mid'=>$mid,'uniacid'=>$_SESSION['uniacid']),'price');
					if($buyfee>=$this->setting['money']){
						$ispass=true;
						$this->apply_agent($member['mid']);
						if($this->setting['become_check'] && $isexi){
							exi('申请正在审核请耐心等待。','error','jy_boaoshop/apply/');
						}
					}elseif($isexi){
						exi('你还不是'.$page_setting['tagent'].'，请前往申请！','error','jy_boaoshop/apply/');
					}
				}else{
					if($isexi){
						exi('你还不是'.$page_setting['tagent'].'，请前往申请！','error','jy_boaoshop/apply/');
					}
				}
				if($ispass){
					exi('','','jy_boaoshop/index/');
				}
			}elseif($member['stop'] && $isexi){
				if($isset){
						return true;
				}
				exi('你的'.$page_setting['tagent'].'身份已禁用！','error','jy_boaoshop/apply/');
			}elseif((!$member['realname'] || !$member['mobile']) && $isexi){
				if($isset){
					return true;
				}
				if($this->setting['become_reg']==1){
					exi('请先完善信息','error','jy_boaoshop/info/');
				}else{
					
				}
			}
			return $member;
	}
	public function checklogin(){
		if(!$_SESSION['uid']){
			exi('','','jy_boaoshop/login/');
		}
		return true;
	}
	public function member_update($mid,$update=array()){
		pdo_update('jy_boaoshop_member',$update,array('mid'=>$mid,'uniacid'=>$_SESSION['uniacid']));
		return true;
	}
	public function check_myshop($mid=0){
		return false;
	}
	/*
		会员注册
	*/
	public function register($member=array()){
		if(!$member['uniacid']){
			$member['uniacid']=$_SESSION['uniacid'];
		}
		if(!$member['mid']){
			$member['mid']=$_SESSION['uid'];
		}		
		if(!$member['createtime']){
			$member['createtime']=TIMESTAMP;
		}
		if(!$member['mid']){
			return error('分红商会员注册失败，缺少会员ID.');
		}
		$ismid=$this->get('member',array('mid'=>$member['mid']),array('mid'));
		if(!$ismid){
			$this->insert('member',$member);
		}
		if($member['agent_id']){
			$this->set_parent($member['mid'],$member['agent_id']);
		}
		if(!$member['agent_id'] && $_SESSION['this']=='custom'){
			$agent_id=pdo_getcolumn('core_members',array('id'=>$_SESSION['uid']),'fromuser');
			$agent_id=$agent_id?:$_SESSION['fromuser'];
			if($agent_id){
				$this->set_parent($member['mid'],$agent_id);
			}
		}
		//如果成为分红商无条件，此处自动申请成为分红商
		if($this->setting['become']==0 || $this->session('becomefromuser')){
			//分红商无需审核，此处自动审核
			$this->apply_agent($member['mid'],true);
		}
	}
	/*
		设置上下级关系
	*/
	public function set_parent($mid=0,$parent_id=0,$ischange=false){
		$mid=$mid?:$_SESSION['uid'];
		$member=$this->get('member',array('mid'=>$mid),array('mid','is_agent','team_mid','level_id','agent_id','createtime'));
		$old_agent_id=$member['agent_id'];
		$isuser=pdo_getcolumn('core_members',array('id'=>$parent_id,'uniacid'=>$_SESSION['uniacid']),'id');
		//如果不存在该会员，已经是分红商或已经有上级了，取消执行。
		if(($old_agent_id || !$isuser || ($member['is_agent'] && $member['createtime']+60<TIMESTAMP)) && !$ischange){
			return true;
		}
		//如果他的上级是我
		$ta_agent_id=$this->getcolumn('member',array('mid'=>$parent_id,'uniacid'=>$_SESSION['uniacid']),'agent_id');
		if($ta_agent_id==$mid){
			if($ischange){
				exi('上级的上级不能是你自己！','error');
			}
			return true;
		}
		//如果上级是自己，上级ID归零
		if($mid==$parent_id){
			if($ischange){
				exi('上级不能是你自己！','error');
			}
			return true;
		}
		$this->update('member',array('agent_id'=>$parent_id),array('mid'=>$mid,'uniacid'=>$_SESSION['uniacid']));
		$agent_id=$old_agent_id;
		$this->update_agent_level($agent_id);
		return true;
	}
	/*
		申请成为分红商
	*/
	public function apply_agent($mid,$noapply=false){
		$member=$this->pdo_get('member',array('mid'=>$mid,'uniacid'=>$_SESSION['uniacid']));
		if($member['sale_mid']){
			exi('已经是直销用户，不能成为分红商。','error');
		}
		$apply=$this->get('apply',array('mid'=>$mid));
		if($apply && $apply['status']!=2){
			if($apply['status']==1){
				$member_update=array(
					'is_agent'=>1,
					'agenttime'=>TIMESTAMP,
				);
				$this->update('member',$member_update,array('mid'=>$apply['mid'],'uniacid'=>$_SESSION['uniacid']));
				$this->upyao_fee($mid);
				$this->model('notice')->notice_fenxiao_add($mid);
			}
			return;
		}
		if($apply['status']!=2){
			$new_apply=array(
				'uniacid'=>$_SESSION['uniacid'],
				'mid'=>$mid,
				'status'=>0,
				'createtime'=>TIMESTAMP,
			);
			$this->insert('apply',$new_apply);
			$apply_id=$this->insertid();
		}else{
			$this->update('apply',array('status'=>0),array('mid'=>$mid,'uniacid'=>$_SESSION['uniacid']));
			$apply_id=$apply['id'];
		}
		if(!$this->setting['become_check']){
			//分红商无需审核，此处自动审核
			$this->check_apply($apply_id,1);
		}
		return true;
	}
	/*
		审核分红商
	*/
	public function check_apply($apply_id,$status,$remark=''){
		if(!$apply_id || !$status){
			return;
		}
		$apply=$this->get('apply',array('id'=>$apply_id));
		if(!$apply){
			return;
		}
		$update=array(
			'status'=>$status,
			'complete_time'=>TIMESTAMP,
		);
		if($update['status']==1){
			//审核通过，修改会员状态，修改上线相关数据
			$member_update=array(
				'is_agent'=>1,
				'agenttime'=>TIMESTAMP,
			);
			$this->update('member',$member_update,array('mid'=>$apply['mid'],'uniacid'=>$_SESSION['uniacid']));
			$this->upyao_fee($apply['mid']);
			//审核通过，此处增加上线的相关数据
			$agent_id=$this->getcolumn('member',array('mid'=>$apply['mid'],'uniacid'=>$_SESSION['uniacid']),'agent_id');
			for($i=0;$i<$this->setting['level'];$i++){
				if(!$agent_id){
					break;
				}
				$agent_update=array('agent_num +='=>1);
				if($i==0){
					$agent_update['agent_num_next +=']=1;
				}
				$this->update('member',$agent_update,array('mid'=>$agent_id,'uniacid'=>$_SESSION['uniacid']));
				$this->update_agent_level($agent_id);
				$agent_id=$this->getcolumn('member',array('mid'=>$agent_id,'uniacid'=>$_SESSION['uniacid']),'agent_id');
			}
		}else{
			$update['remark']=$remark;
		}
		$this->update('apply',$update,array('id'=>$apply_id));
		return true;
	}
	/*
		禁用分红商
	*/
	public function stop_agent($agent_id){
		$this->update('member',array('stop'=>1),array('mid'=>$agent_id,'uniacid'=>$_SESSION['uniacid']));
	}
	/*
		恢复分红商
	*/
	public function start_agent($agent_id){
		$this->update('member',array('stop'=>0),array('mid'=>$agent_id,'uniacid'=>$_SESSION['uniacid']));
	}
	/*
		获取会员的各项参数
		
		问题：开启分红内购时
			推广订单如何算？
			下线如何算？
			
			计算下线时，分红级数在设置的级数基础上-1，其他不变
			计算推广订单时，在上面的基础上+自己的订单
	*/
	public function get_member($mid){
		$res=array();
		//获取一级下线数量
		$members=$this->getall('member',array('uniacid'=>$_SESSION['uniacid'],'agent_id'=>$mid),array('mid','is_agent'),'mid');		
		if(!$members){
			$res=array(
				'member_num'=>'0',
				'agent_num'=>'0',
				'order_price'=>'0',
				'order_num'=>'0',
				'myorder_price'=>'0',
				'order_price_next'=>'0',
				'order_num_next'=>'0',
				'member_num_next'=>'0',
				'agent_num_next'=>'0',
			);
			return $res;
		}
		//获取直属下级分红商数量
		$res['agent_num_next']=$this->count('member',array('uniacid'=>$_SESSION['uniacid'],'is_agent'=>1,'agent_id'=>$mid));
		$res['member_num_next']=count($members);
		$member_ids=array_keys($members);
		$res['order_num_next']=$this->count('order',array('mid'=>$member_ids));
		$res['order_price_next']=$this->sum('order',array('mid'=>$member_ids),'order_price');
		//获取下线总数，向下遍历系统设置的指定分红层数
		$commission_level=intval($this->setting['level']);
		if($this->setting['self_commission']){
			//开启分红内购
			$commission_level=$commission_level-1;
		}
		if($commission_level>1){
			$next_ids=$member_ids;
			for($i=1;$i<$commission_level;$i++){
				$next_members=$this->getall('member',array('uniacid'=>$_SESSION['uniacid'],'agent_id'=>$next_ids),array('mid','is_agent'),'mid');
				if(!$next_members){
					break;
				}
				$members=array_merge($next_members,$members);
				$next_ids=array_keys($next_members);
				$member_ids=array_merge($next_ids,$member_ids);
			}
		}
		$res['member_num']=count($member_ids);
		$res['order_num']=$this->count('order',array('mid'=>$member_ids));
		$res['order_price']=$this->sum('order',array('mid'=>$member_ids),'order_price');
		$res['myorder_price']=$this->sum('order',array('mid'=>$mid),'myorder_price');
		$res['agent_num']=0;
		foreach($members as $member){
			if($member['is_agent']){
				$res['agent_num']++;
			}
		}
		if($this->setting['self_commission']){
			//开启分红内购，此处加上用户自己的订单作为推广订单的一部分
			$self_order_num=$this->count('order',array('mid'=>$mid));
			$self_order_money=$this->sum('order',array('mid'=>$mid),'order_price');
			$res['order_num_next']=$self_order_num;
			$res['order_price_next']=$self_order_money;
			$res['order_num']+=$self_order_num;
			$res['order_price']+=$self_order_money;
		}
		return $res;
	}
	/*
		升级分红商等级
		先检测会员身份是否为正常分红商
		然后获取分红商当前等级的下一等级升级条件
		然后逐个条件对比，看是否满足升级条件
		如果全部满足，则升级到相应等级
		
		何时触发升级分红商等级检测呢？
		
	*/
	public function update_agent_level($mid,$orderid=0){
		//
		$member=$this->get('member',array('mid'=>$mid,'uniacid'=>$_SESSION['uniacid']));
		if(!$member['is_agent'] || $member['stop']){
			return;
		}
		$level=$this->get('level',array('id'=>$member['level_id']));
		$parameter=array(
			'params'=>array('uniacid'=>$_SESSION['uniacid'],'level >'=>$level['level']),
			'orderby'=>'level desc',
		);
		$levels=$this->getall('level',$parameter['params'],'','',$parameter['orderby']);
		if(empty($levels)){
			return;
		}
		$downmids=$this->getteamids($member['mid']);
		if(!$downmids){
			$downmids=-1;
		}
		$zhituimids=$this->getall('member',array('agent_id'=>$member['mid'],'uniacid'=>$_SESSION['uniacid']),'mid','mid');
		if($zhituimids){
			$zhituimids=array_keys($zhituimids);
		}else{
			$zhituimids=-1;
		}
		$level_up_types=$this->model()->current_level_up_types();//获取当前设置的分红商等级升级条件
		$is_level_up_one=$this->setting['is_level_up_one'];
		foreach($levels as $lv){
			$conditions=json_decode($lv['conditions'],true);
			if(!$level_up_types || !$lv['id']){
				break;
			}
			$up=true;
			foreach($level_up_types as $type){
				if($type=='order_price' && $conditions['order_price']){
					//团订单总金额（元）,
					$order_price=pdo_getsum('jy_boaoshop_order',array('uniacid'=>$_SESSION['uniacid'],'ispay'=>1,'mid'=>$downmids),'price');
					//file_put_contents(ROOT_D.'/1.TXT',$type.'~~'.$order_price."\n",FILE_APPEND);
					if($order_price<$conditions['order_price'] && $conditions['order_price']){
						$up=false;
						break;
					}
				}elseif($type=='oneorder_price' && $conditions['oneorder_price']){
					//直推总业绩(小社区)
					$oneorder_price=pdo_getsum('jy_boaoshop_order',array('uniacid'=>$_SESSION['uniacid'],'ispay'=>1,'mid'=>$zhituimids),'price');
					//file_put_contents(ROOT_D.'/1.TXT',$type.'~~'.$oneorder_price."\n",FILE_APPEND);
					if($oneorder_price<$conditions['oneorder_price'] && $conditions['oneorder_price']){
						$up=false;
						break;
					}
				}
			}
			if($up){
				$next_level=$lv;
				break;
			}
		}
		if($up){
			$update=array(
				'level_id'=>$next_level['id'],
			);
			$this->update('member',$update,array('mid'=>$mid,'uniacid'=>$_SESSION['uniacid']));
		}
		return true;
	}
	public function check_redfee($member=array()){
		$fee_3=$this->sum('commission',array('type'=>3,'uniacid'=>$_SESSION['uniacid'],'mid'=>$member['mid']),'money');
		if($fee_3>=$member['redfee']){
			return false;
		}
		return true;
	}
	public function getteamids($teammid=0,$level=0){
		$teammid=$teammid?:$_SESSION['uid'];
		$newmembers=array($teammid=>$teammid);
		$newteammids=$teammid;
		$level=$level?:$this->setting['level'];
		$level=$level?:7;
		for($i=1;$i<$level;$i++){
			$members=$this->getall('member',array('uniacid'=>$_SESSION['uniacid'],'agent_id'=>$newteammids),array('mid'),'mid');
			if($members){
				foreach($members as $key=>$item){
					$newmembers[$key]=$key;
				}
				$newteammids=array_keys($members);
			}else{
				break;
			}
		}
		if($newmembers){
			$teamids=array_keys($newmembers);
		}else{
			$teamids=array();
		}
		return $teamids;
	}
}